//
//  NSDate+SMC.m
//  SMCKit
//
//  Created by Sim on 13-1-9.
//  Copyright (c) 2013年 3gtv.net. All rights reserved.
//

#import "NSDate+QL.h"

@implementation NSDate (QL)


// 取值范围0 ~ 6 对应 (周日 ~ 周六)
+(NSInteger)ql_weekday:(NSDate*)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = nil;
    NSUInteger unitFlags = NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit;
    comps = [calendar components:unitFlags fromDate:date];
    NSInteger week = [comps weekday] - 1;
    return week;
}

+(NSArray*)ql_getThisWeekAllDates
{
    NSMutableArray *days = [NSMutableArray array];
    NSDate *dateNow = [NSDate date];
    NSInteger weekdayToday = [NSDate ql_weekday:dateNow];
    long dayEarlerCount = weekdayToday ;//前面还有dayEarlerCount天
    NSDate *_tmpDate;
    
    int secOfDay = 24 *60 *60;
    NSDate *_sundayThisWeek = [NSDate dateWithTimeIntervalSinceNow:(-dayEarlerCount * secOfDay)];
    for(int _idx = 0;_idx <7;++_idx){
        _tmpDate = [_sundayThisWeek dateByAddingTimeInterval:_idx * secOfDay];
        [days addObject:_tmpDate];
    }
    return days;
}

-(BOOL)ql_isLaterDate:(NSDate*)date
{
    NSTimeInterval _t1 = [self timeIntervalSince1970];
    NSTimeInterval _t2 = [date timeIntervalSince1970];
    return (_t1 >=_t2);
}

-(BOOL)ql_isEarlyerDate:(NSDate*)date
{
    NSTimeInterval _t1 = [self timeIntervalSince1970];
    NSTimeInterval _t2 = [date timeIntervalSince1970];
    return (_t1 <_t2);
}

-(BOOL)ql_isBetweenDate:(NSDate*)start andDate:(NSDate*)end
{
    NSTimeInterval _t = [self timeIntervalSince1970];
    NSTimeInterval _ts = [start timeIntervalSince1970];
    NSTimeInterval _te = [end timeIntervalSince1970];
    return (_ts < _t && _t <_te);
}

+(NSDate*)ql_dateWithString:(NSString *)datestr
{
    if (datestr == nil) {
        return nil;
    }
    NSDateFormatter *_formatter = [[NSDateFormatter alloc] init];
    [_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *_tmpDate = [_formatter dateFromString:datestr];
    return _tmpDate;
}

-(NSString*)ql_ToString
{
    NSDateFormatter *_formatter = [[NSDateFormatter alloc] init];
    [_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *_tmpstr = [_formatter stringFromDate:self];
    return _tmpstr;
}

-(NSString*)ql_ToStringWithFormat:(NSString*)format
{
    NSDateFormatter *_formatter = [[NSDateFormatter alloc] init];
    [_formatter setDateFormat:format];
    NSString *_tmpstr = [_formatter stringFromDate:self];
    return _tmpstr;
}

-(BOOL)ql_isToday
{
    BOOL isToday = NO;
    NSString *strThisDate = [self ql_ToStringWithFormat:@"yyyy-MM-dd"];
    NSString *strToday = [[NSDate date] ql_ToStringWithFormat:@"yyyy-MM-dd"];
    isToday = [strThisDate isEqualToString:strToday];
    return isToday;
}
@end
